package com.yc.damai.web.filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.google.gson.Gson;
import com.yc.damai.bean.Result;

/**
 * 过滤是实现了 Filter 接口的类
 * 
 * 组件生命周期： init  destroy
 * 
 * doFilter 业务方法 ==》 对请求进行拦截
 * 
 * urlPatterns 定义要拦截的资源名  => String[]
 * 
 */
@WebFilter(urlPatterns = { "/cart.html" , "/olist.html", "/addCart.s"} )
public class LoginFilter implements Filter {


	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		System.out.println("=========== LoginFilter destroy ===============");
	}

	/**
	 * 过滤方法（拦截方法）
	 *     ServletRequest request,    	请求对象
	 * HttpServletRequest
	 *     ServletResponse response,  	响应对象
	 * HttpServletResponse 
	 * FilterChain chain		  		过滤器链
	 * 
	 * 
	 * 
	 * 
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		HttpServletResponse httpResponse = (HttpServletResponse) response;
		HttpSession session = httpRequest.getSession();
		// 判断是否登录
		if(session.getAttribute("loginedUser")== null) {
			
			// 判断 ajax 请求
			/**
			 * ajax 请求头信息： 
			 * Accept: application/json, text/plain,
			 * 普通的 html 请求 （浏览器地址栏输入产生的请求） 
			 * Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/
			 * 
			 * Accept——接收， 我（浏览器）可以接受的服务器的响应的内容
			 */
			String value = httpRequest.getHeader("Accept");
			request.setCharacterEncoding("utf-8");
			response.setCharacterEncoding("utf-8");
			response.setContentType("text/html;charset=utf-8");
			if(value.contains("json")) {
				Result result = new Result(0,"请先登录系统");
				String json = new Gson().toJson(result);
				response.getWriter().append(json);
			} else {
				// 打印当前项目(工程)名
				System.out.println(httpRequest.getServletContext().getContextPath());
				// 打印当前的资源地址
				System.out.println(httpRequest.getServletPath());
				// 获取当前请求访问的地址， 这个地址就是登录成功后要跳转的地址
				value = httpRequest.getServletContext().getContextPath() + 
						httpRequest.getServletPath();
				// 保存到会话中
				httpRequest.getSession().setAttribute("Referer", value);
				httpResponse.sendRedirect("login.html");
			}
			// 页面跳转  ！= 方法执行结束， 必须return
			return;
		}
		// 正常业务逻辑才能访问目标资源
		chain.doFilter(request, response);
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		System.out.println("=========== LoginFilter init ===============");
	}

}
